package com.example.demo1.controller;

import com.example.demo1.dao.EmpMapper;
import com.example.demo1.enums.EmpInfoEnum;
import com.example.demo1.pojo.po.Emp;
import com.example.demo1.pojo.vo.EmpVO;
import com.example.demo1.util.ResultUtil;
import com.fasterxml.jackson.databind.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: 本类用于CRUD员工信息
 * Created by 白相宇 on 2019/12/19 14:38
 */
@RestController
@Slf4j
public class EmpController {

    @Autowired
    private EmpMapper empMapper;

    /**
     * 根据id查询员工信息
     *
     * @param id : 参数id
     * @return : 返回员工信息
     */
    @GetMapping("/getEmpById")
    public ResultUtil getEmpById(@RequestParam Integer id) {
        if (id == null) {
            return ResultUtil.fail(EmpInfoEnum.idIsNull.getStatusCode(), EmpInfoEnum.idIsNull.getStatusMessage());
        }
        try {
            Emp emp = empMapper.getEmpById(id);
            EmpVO empVO = new EmpVO();
            setValue(emp, empVO);
            BeanUtils.copyProperties(emp, empVO);
            if (emp != null) {
                return ResultUtil.success(empVO);
            } else {
                return ResultUtil.success(EmpInfoEnum.resultNotFound.getStatusMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.fail(EmpInfoEnum.queryExceptionBYiD.getStatusCode(), EmpInfoEnum.queryExceptionBYiD.getStatusMessage());
        }
    }

    /**
     * 查询所有信息
     *
     * @return
     */
    @GetMapping("/getAll")
    public ResultUtil getAll() {
        try {
            List<Emp> list = empMapper.getAll();
            log.info("=======" + list);
            return ResultUtil.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.fail(EmpInfoEnum.queryExceptionBYiD.getStatusCode(), EmpInfoEnum.queryExceptionBYiD.getStatusMessage());
        }
    }

    /**
     * 提供本类中使用
     *
     * @param emp
     * @param empVO
     */
    private void setValue(Emp emp, EmpVO empVO) {
        empVO.setEmpAge(emp.getEmpAge());
        empVO.setEmpName(emp.getEmpName());
        empVO.setEmpSex(emp.getEmpSex());
        empVO.setEmpSalary(emp.getEmpSalary());
    }
}
